package com.hnyyac.ad.mds.views_notload



import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.ViewGroup

import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.CSJAdError
import com.bytedance.sdk.openadsdk.CSJSplashAd
import com.bytedance.sdk.openadsdk.TTAdNative.CSJSplashAdListener
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.mediation.MediationConstant
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.bytedance.sdk.openadsdk.mediation.ad.MediationSplashRequestInfo
import com.hnyyac.ad.mds.KadControler
import com.hnyyac.ad.mds.manager.MyWindowUtil

import kotlinx.coroutines.*
import kotlinx.coroutines.selects.select
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicBoolean

class DoubleSplashAdNew(
    activity: Activity,
    private val listener: IAdviewNotLoadSplashListener
) {
    // 弱引用
    private val weakActivity = WeakReference(activity)
    private var weakContainer: WeakReference<ViewGroup>? = null

    // 广告对象
    private var primaryAd: CSJSplashAd? = null
    private var secondaryAd: CSJSplashAd? = null
    private var currentAdUnitId: String? = null
    private var currentAdTag: String? = null
    private var currentPosition: Int = 0

    // 协程控制
    private val scope = MainScope()
    private var loadJob: Job? = null
    private var totalTimeoutJob: Job? = null

    // 常量
    private val TAG = "DoubleSplashAd"
    private val MAIN_AD_TAG = "主广告"
    private val BACKUP_AD_TAG = "备用广告"
    private val handler by lazy { Handler(Looper.getMainLooper()) }
    private val isTimeoutHandled = AtomicBoolean(false)
    fun loadDoubleSplashAd(
        primaryAdUnitId: String,
        secondaryAdUnitId: String,
        container: ViewGroup,
        timeout: Int = 15000,
        position: Int = 0,
        isHot: Boolean = false
    ) {
        currentPosition = position
        weakContainer?.get()?.removeAllViews()
        weakContainer = WeakReference(container)

        // 总超时控制
        totalTimeoutJob = scope.launch {
            delay(timeout.toLong())
            if (isTimeoutHandled.compareAndSet(false, true)) {
                if (!isHot){
                    KadControler.fristFillCache()
                }

            }
            listener.onError("广告加载超时")
            safeGoToMainActivity()

        }

        loadJob = scope.launch {
            try {
                // 并行加载两个广告
                val primaryDeferred = async { loadAd(primaryAdUnitId, MAIN_AD_TAG,isHot) }
                val secondaryDeferred = async { loadAd(secondaryAdUnitId, BACKUP_AD_TAG,isHot) }

                // 等待任一广告加载成功
                select<Unit> {
                    primaryDeferred.onAwait { success ->
                        if (success) showAd(primaryAd!!, primaryAdUnitId, MAIN_AD_TAG,isHot)
                    }
                    secondaryDeferred.onAwait { success ->
                        if (success && primaryAd == null) {
                            showAd(secondaryAd!!, secondaryAdUnitId, BACKUP_AD_TAG,isHot)
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "广告加载异常: ${e.message}")
                safeGoToMainActivity()
            }
        }
    }
    private val isLoadFailHandled = AtomicBoolean(false)
    private suspend fun loadAd(adUnitId: String, tag: String, isHot: Boolean): Boolean {
        Log.e(TAG, "开始加载广告")
        // 在 IO 线程检查 Activity 状态（非广告 SDK 操作）
        val activity = withContext(Dispatchers.IO) {
            weakActivity.get()?.takeUnless { it.isFinishing || it.isDestroyed }
        } ?: return false

        // 切换到主线程执行广告 SDK 相关操作
        return withContext(Dispatchers.Main) {
            val deferred = CompletableDeferred<Boolean>()
            listener.onTrigger(adUnitId)

            val (width, height) = MyWindowUtil.getScreenSize(activity)
            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitId)
                .setImageAcceptedSize(width, height)
                .setMediationAdSlot(
                    MediationAdSlot.Builder().build()
                )
                .build()

            TTAdSdk.getAdManager().createAdNative(activity).loadSplashAd(
                adSlot,
                object : CSJSplashAdListener {
                    override fun onSplashLoadSuccess(ad: CSJSplashAd?) {
                        Log.e(TAG, "加载广告onSplashLoadSuccess")
                        if (ad == null) {
                            deferred.complete(false)
                            return
                        }
                        when (tag) {
                            MAIN_AD_TAG -> {
                                primaryAd?.mediationManager?.destroy()
                                primaryAd = ad
                            }
                            BACKUP_AD_TAG -> {
                                secondaryAd?.mediationManager?.destroy()
                                secondaryAd = ad
                            }
                        }
                        deferred.complete(true)
                    }

                    override fun onSplashLoadFail(error: CSJAdError) {
                        Log.w(TAG, "$tag 加载失败: ${error.code} - ${error.msg}")
                        listener.onError("${error.msg} (code=${error.code})")
                        if (isLoadFailHandled.compareAndSet(false, true)) {
                            if (!isHot){
                                KadControler.fristFillCache()
                            }
                        }
                        deferred.complete(false)
                    }

                    override fun onSplashRenderSuccess(ad: CSJSplashAd) {
                        listener.onSuccess(ad, adUnitId)
                    }

                    override fun onSplashRenderFail(ad: CSJSplashAd, error: CSJAdError) {
                        Log.w(TAG, "$tag 渲染失败: ${error.code} - ${error.msg}")
                        listener.onError("${error.msg} (code=${error.code})")
                        when (tag) {
                            MAIN_AD_TAG -> primaryAd = null
                            BACKUP_AD_TAG -> secondaryAd = null
                        }
                    }
                },
                3750
            )

            deferred.await()
        }
    }
    private val isFirstFillCacheExecuted = AtomicBoolean(false)
    private fun showAd(ad: CSJSplashAd, adUnitId: String, tag: String, isHot: Boolean) {
        val activity = weakActivity.get() ?: return
        val container = weakContainer?.get() ?: return

        if (activity.isFinishing) {
            return
        }

        currentAdUnitId = adUnitId
        currentAdTag = tag

        totalTimeoutJob?.cancel() // 取消总超时计时

        ad.setSplashAdListener(object : CSJSplashAd.SplashAdListener {
            override fun onSplashAdShow(ad: CSJSplashAd) {
                listener.onAdShow(ad, adUnitId, currentPosition)
                if (isFirstFillCacheExecuted.compareAndSet(false, true)) {
                    if (!isHot){
                        KadControler.fristFillCache()
                    }
                }
            }

            override fun onSplashAdClick(ad: CSJSplashAd) {
                listener.onAdClick(ad, adUnitId)
            }

            override fun onSplashAdClose(ad: CSJSplashAd, closeType: Int) {
                listener.onAdClose(ad, adUnitId)
                ad.mediationManager?.destroy()

                handler.postDelayed({
                    if (weakActivity.get()?.isFinishing != false) return@postDelayed

                    val nextAd = when (tag) {
                        MAIN_AD_TAG -> secondaryAd?.also { primaryAd = null }
                        BACKUP_AD_TAG -> primaryAd?.also { secondaryAd = null }
                        else -> null
                    }

                    nextAd?.let {
                        showAd(it, currentAdUnitId ?: "",
                            if (tag == MAIN_AD_TAG) BACKUP_AD_TAG else MAIN_AD_TAG,isHot)
                    } ?: safeGoToMainActivity()
                }, 300)
            }
        })

        activity.runOnUiThread {
            container.removeAllViews()
            ad.splashView?.let {
                container.addView(it)
            } ?: run {
                tryShowBackupAdOrFinish(isHot)
            }
        }
    }



    fun onDestroy() {
        synchronized(this) {
            primaryAd?.mediationManager?.destroy()
            secondaryAd?.mediationManager?.destroy()
            weakContainer?.get()?.removeAllViews()
        }
        loadJob?.cancel()
        totalTimeoutJob?.cancel()
        scope.cancel()
    }

    private fun tryShowBackupAdOrFinish(isHot: Boolean) {
        val activity = weakActivity.get() ?: return
        if (activity.isFinishing) {
            safeGoToMainActivity()
            return
        }

        if (currentAdTag == MAIN_AD_TAG && secondaryAd != null) {
            showAd(secondaryAd!!, currentAdUnitId ?: "", BACKUP_AD_TAG, isHot)
        } else {
            safeGoToMainActivity()
        }
    }

    private fun safeGoToMainActivity() {
        if (weakActivity.get()?.isFinishing != false) return
        listener.goMain()
    }

    private fun createDefaultRequestInfo(): MediationSplashRequestInfo {
        return object : MediationSplashRequestInfo(
            MediationConstant.ADN_PANGLE,
            "891932848",
            "5707672",
            ""
        ) {}
    }
}